package com.picturestory.client.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.picturestory.client.android.util.Constants;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class HttpRequester extends Activity {
	
	private static final String TAG = HttpRequester.class.getSimpleName();
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.i(Constants.LOGTAG, TAG + " receives the result=" + ret);
			setResult(RESULT_OK, new Intent(HttpRequester.this, HttpConnectionTest.class).putExtra("result", ret));
			finish();
		}
		
	};
	private String ret;

	private String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the
         * Reader.read(char[] buffer) method. We iterate until the Reader
         * return -1 which means there's no more data to read. We use the
         * StringWriter class to produce the string.
         */
        if (is != null) {
                Writer writer = new StringWriter();

                char[] buffer = new char[1024];
                try {
                        Reader reader = new BufferedReader(new InputStreamReader(
                                        is, "UTF-8"));
                        int n;
                        while ((n = reader.read(buffer)) != -1) {
                                writer.write(buffer, 0, n);
                        }
                } finally {
                        is.close();
                }
                return writer.toString();
        } else {
                return "";
        }
}
	
	private String get(String url) {
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = null;
        
        HttpGet httpGet = new HttpGet(url);
        
        //
        httpGet.setHeader("Accept", "application/json");
        
        InputStream is = new InputStream() {
                @Override
                public int read() throws IOException {
                        return 0;
                }
        };
        
        Log.i(Constants.LOGTAG, TAG + " executes a GET method");
        
        //mProgressDialog.show(this, "Processing ...", "Getting Employee data", true, false);
        try {
                response = client.execute(httpGet);
                is = response.getEntity().getContent();
        } catch (ClientProtocolException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
        
        Log.i(Constants.LOGTAG, TAG + " finishes executing a GET method");
        
        try {
                result = convertStreamToString(is);
        } catch (IOException e) {
                e.printStackTrace();
                result = "You have failed!!";
        }
        
        Log.i(Constants.LOGTAG, TAG + " returns the result of a GET method = " + result);
        //mProgressDialog.dismiss();
        return result;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Intent i = getIntent();
		Log.i(Constants.LOGTAG, TAG + " starts to handle a HTTP request");
		
		Bundle b = i.getExtras();
		
		final String url = "http://picture-history.appspot.com/employee/eric/kim";
		Log.i(Constants.LOGTAG, TAG + " issues a GET method on url=\"" + url + "\"");
		
		
		new Thread() {

			@Override
			public void run() {
				ret = get(url);
				mHandler.handleMessage(mHandler.obtainMessage());
			}
			
		}.start();

		
	}

	
	
}
